package com.egoo.ticket.server.utils.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: victor_tang
 * @Date: 2021/2/2 16:52
 * @Description: 处理sql注入工具类
 */
@Component
@Slf4j
public class HandleSqlInjectionUtil {
	@Value("${sql.filter-switch}")
	private Boolean filterSwitch;

	// 正则匹配sql关键字
	public String regexStr = "and,exec,execute,insert,select,delete" +
			",update,count,drop,%,chr,mid,master,truncate," +
			"char,declare,sitename,net user,xp_cmdshell,;,or,-,+,,,like',and" +
			",exec,execute,insert,create,drop" +
			",table,from,grant,use,group_concat,column_name,information_schema.columns" +
			",table_schema,union" +
			",where,select,delete,update,order,by,count," +
			"chr,mid,master,truncate,char,declare,or,;,-,--,+,,,like,//,/,%,#";
	/**
	 * 返回经过防注入处理的字符串
	 *
	 * @param request
	 * @param name
	 * @return
	 */
	public String getParameter(HttpServletRequest request, String name) {
		return filter(request.getParameter(name));
	}
	/**
	 * TODO 把SQL关键字替换为空字符串
	 * @author: victor_tang
	 * @createtime: 2021/2/3 14:18
	 * @param param 1
	 * @return: java.lang.String
	 */
	public String filter(String param) {
		if (!filterSwitch) {
			// sql过滤开关未开启时，直接退出
			return param;
		}
		if (StringUtils.isEmpty(param)) {
			return param;
		}
		param = param.toLowerCase();
		String returnStr = param;
		String[] split = regexStr.split(",");
		for (String str : split) {
			int index = param.indexOf(str);
			if (index!=-1) {
				returnStr = returnStr.replaceAll(str,"");
			}
		}
		return returnStr;
	}
}
